package solution.design;

import java.util.LinkedHashMap;

/**
 * @author zhangmin
 * @create 2021-09-28 17:32
 */
public class LRUCache {
    private int capacity;
    LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>();
    public LRUCache(int capacity) {
        this.capacity=capacity;
    }

    private void makeRecently(int key) {
        int val=cache.get(key);
        // 删除 key，重新插入到队尾
        cache.remove(key);
        cache.put(key,val);
    }
    public int get(int key) {
        if (!cache.containsKey(key)){
            return -1;
        }
        makeRecently(key);
        return cache.get(key);
    }

    public void put(int key, int value) {
        if (cache.containsKey(key)){
            // 修改 key 的值
            cache.put(key,value);
            makeRecently(key);
            return;
        }
        if (cache.size()>=capacity){
            // 链表头部就是最久未使用的 key
            int oldest=cache.keySet().iterator().next();
            cache.remove(oldest);
        }
        // 将新的 key 添加链表尾部
        cache.put(key,value);
    }
}
